/*
 * User manager interface effects and Ajax functions
 */

/*********************************************
 *                 PART ONE                  *
 *             Interface effects             *
 *********************************************/

// Initialize
new Asset.css('modules/admin/users2/custom.css');
var hovered = 0;
var tip = '';
var selected = [];

// Adding overlay DIVs to the DOM
window.addEvent('domready', userDom);

// Positioning and resizing overlay DIVs on window resize
window.addEvent('resize', function() {
    $('mae_overlay').setStyles({
        'width': window.getScrollWidth()+'px',
        'height': (window.webkit) ? window.getHeight()+'px' : window.getScrollHeight()+'px'
    });
    $('mae_box').setStyles({
        'top': window.getScrollTop()+((window.getHeight()/2)-150)+'px',
        'left': window.getScrollLeft()+((window.getWidth()/2)-215)+'px'
    });
});

// Button effects
$$('.user').each(function(o) {
    o.addEvent('mouseenter', userHoverup);
    o.addEvent('mouseleave', userHoverdown);
});
function userHoverup() {
    this.effect('border-color', {duration: 250, wait: false}).start('#FFF','#999');
    this.getLast().effects({duration: 250, wait: false}).start({'background-color':['#FFF','#999'], 'color':['#000','#FFF']});
    updateHover(this);
}
function userHoverdown() {
    this.effect('border-color', {duration: 250, wait: false}).start('#999','#FFF');
    this.getLast().effects({duration: 250, wait: false}).start({'background-color':['#999','#FFF'], 'color':['#FFF','#000']});
}

// Show/hide the overlay
function userShow() {
    userHideFlashes();
    $('mae_overlay').setStyle('display','block').effect('opacity', {duration: 400}).start(0, 0.8);
    $('mae_box').setStyle('display','block').effect('opacity', {duration: 400}).start(0, 1);
}
function userHide() {
    $('mae_overlay').effect('opacity', {duration: 400}).start(0.8, 0).chain(function() {$('mae_overlay').setStyle('display','none');userShowFlashes();});
    $('mae_box').effect('opacity', {duration: 400}).start(1, 0).chain(function() {$('mae_box').setStyle('display','none');});
}

// Show/hide every flash element (eg. sIFR)
function userHideFlashes() {
    $$('object').each(function(x) {x.setStyle('visibility', 'hidden');});
    $$('embed').each(function(x) {x.setStyle('visibility', 'hidden');});
    $$('h2')[0].setStyle('display', 'none');
}
function userShowFlashes() {
    $$('object').each(function(x) {x.setStyle('visibility', 'visible');});
    $$('embed').each(function(x) {x.setStyle('visibility', 'visible');});
    $$('h2')[0].setStyle('display', 'block');
}
// Creates the tooltips
function updateTips() {
    $$('.tool-tip').remove();

    tip = new Tips($$('.user').filter(function(i) { return i.hasClass('real'); }), {
        initialize: function() {
            this.fx = new Fx.Style(this.toolTip, 'opacity', {wait:false}).set(0);
        },
        onShow: function(tip) {
            var title = new Element('div', {'class': this.options.className+'-title'});
            var titleText = new Element('span').setText(userInfo[hovered].title);

            var text = new Element('div', {'class': this.options.className+'-text'});
            var combined = userInfo[hovered].act+'<br />'+userInfo[hovered].email+'<br />'+userInfo[hovered].reg+'<br />'+userInfo[hovered].priv;
            var textText = new Element('span').setHTML(combined);

            titleText.inject(title);
            textText.inject(text);
            this.toolTip.getFirst().adopt(title).adopt(text);

            this.fx.start(1);
        },
        onHide: function(tip) {
            this.fx.start(0);
        }
    });
}
function userDom() {
    var body = $$('body')[0];

    // Creating DIVs
    var overlay = new Element('div', {
        'id': 'mae_overlay',
        'styles': {
            'display': 'none',
            'width': window.getScrollWidth()+'px',
            'height': (window.webkit) ? window.getHeight()+'px' : window.getScrollHeight()+'px',
            'background-color': '#000',
            'top': 0,
            'left': 0,
            'position': 'absolute',
            'z-index': 1000
        }
    }).setOpacity(0);


    var box = new Element('div', {
        'id': 'mae_box',
        'styles': {
            'display': 'none',
            'width': '400px',
            'height': '330px',
            'position': 'absolute',
            'top': window.getScrollTop()+((window.getHeight()/2)-150)+'px',
            'left': window.getScrollLeft()+((window.getWidth()/2)-215)+'px',
            'z-index': 1000
        }
    }).setOpacity(0);

    var content = new Element('div', {
        'id': 'mae_box_content',
        'styles': {
            'height': '322px',
            'background-color': '#FFF',
            'padding': '10px 10px 0px',
            'overflow': 'auto'
        }
    });
    var design = new Element('div', {
        'id': 'mae_box_mae',
        'styles': {'height': '18px'}
    });

    design.setHTML('<div style="float:left;width:18px;height:18px;cursor:pointer;" onclick="userHide();"><img src="modules/admin/users2/corner_close.png" alt="Close" /></div>'+
                   '<div style="float:left;width:288px;height:18px;background-color:#FFF;">&nbsp;</div>'+
                   '<div style="float:right;width:94px;"><img src="modules/admin/users2/white_mae.png" alt="mae." /></div>'+
                   '<div class="clear"></div>');

    // Adding DIVs to the DOM
    box.adopt(content).adopt(design);
    body.adopt(overlay).adopt(box);

    // Update the tips
    updateTips();
}

// User deletion drag&drop support
function dragMe(pos) {
    var other = (pos=='left') ? 'right' : 'left';
    var drop = $('pile_'+other);
    var dropFx = drop.effect('background-color', {duration: 250, wait: false});

    $$('#pile_'+pos+' .user').each(function(user) {
        user.addEvent('mousedown', function(e) {
            dragEvent(e, {'user': user, 'pos': pos});
        });
    });
}
function dragEvent(e, options) {
    var user = options.user;
    var pos = options.pos;
    var other = (pos=='left') ? 'right' : 'left';
    var drop = $('pile_'+other);
    var dropFx = drop.effect('background-color', {duration: 250, wait: false});

    e = new Event(e).stop();

    var clone = user.clone();
    clone.setStyles(user.getCoordinates([user.getParent()]))
        .setStyles({'opacity': 0.7, 'position': 'absolute'})
        .addEvent('emptydrop', function() {
            clone.remove();
            drop.removeEvents();
        })
        .inject(document.body);

    drop.addEvents({
        'drop': function() {
            drop.removeEvents();
            clone.remove();
            user.clone().inject(drop).addEvent('mousedown', function(e) {
                dragEvent(e, {'user': this, 'pos': other});
            });
            user.remove();
            dropFx.start('#ffffff');
            fillDelete();
        },
        'over': function() {
            dropFx.start('#d1e751');
        },
        'leave': function() {
            dropFx.start('#ffffff');
        }
    });

    var drag = clone.makeDraggable({droppables: [drop]});
    drag.start(e);
}

/*********************************************
 *                 PART TWO                  *
 *              The 'real' work              *
 *********************************************/

$$('.user').each(function(o) {
    o.addEvent('click', userEdit);
});
window.addEvent('mousedown', function(e) {
    // Deselecting all users
    if (!$('user_list').hasChild(e.target)) {
        selected.each(function(i) { userDeselect(i); });
        selected.length = 0;
    }
});

// Button behavior handling
function userEdit(e) {
    e = new Event(e);
    var t = e.target;

    // Setting the user who should be edited
    if (t.hasClass('text')) {
        var user = t.getText();
        t = t.getParent();
    }
    else if (t.getTag() == 'img') {
        var user = t.getParent().getNext().getText();
        t = t.getParent().getParent();
    }
    else var user = t.getLast().getText();

    if (e.control) {
        if (t.hasClass('real')) {
            if (selected.contains(user)) {
                userDeselect(t);
                selected.remove(user);
            } else {
                t.effect('border-color', {duration: 250}).start('#4DBCE9');
                t.getLast().effect('background-color', {duration: 250}).start('#4DBCE9');
                t.removeEvents('mouseenter');
                t.removeEvents('mouseleave');

                // Fix for working tips
                t.addEvent('mouseenter', function(event){
                        updateHover(t);
			this.start(t);
			if (!this.options.fixed) this.locate(event);
			else this.position(t);
		}.bind(tip));
		t.addEvent('mouseleave', tip.end.bind(tip));
                selected.push(user);
            }
        }
    } else {
        // Setting the action
        var userStr = '';
        var q = '';
        if (t.id == 'user_add') var action = 'add';
        else if (t.id == 'user_trash') {
            var action = 'delete';

            // Combining the query string for multiple users deleting
            selected.each(function(u) { q += 'delete[]='+encodeURIComponent(u)+'&'; });
            q = q.substring(0, q.length-1);
        } else {
            var action = 'edit';
            userStr = '&user='+encodeURIComponent(user);
        }

        // The Ajax request
        new Ajax('admin.php?action=users2&do='+action+userStr, {
            method: 'post',
            update: 'mae_box_content',
            data: q,
            evalScripts: true,
            onRequest: function() { $('mae_box_content').setHTML('<img src="modules/admin/users2/throbber.gif" alt="Loading..." />'); userShow(); }
        }).request();
    }
}

// Clearing privileges
function userClearPriv() {
    var o = $('privileges').options;
    for (i=0; i<o.length; i++) {
        o[i].selected = false;
    }
}

// Updating the 'hovered' variable
function updateHover(el) {
    if (!el.id.contains('user_')) hovered = $$('.user').indexOf(el)-2;
}

// Filling the deletion array
function fillDelete() {
    /*
    Pushing version
    deletion.length = 0;
    $$('#pile_right .user').each(function(u) {
        deletion.push(u.getText());
    });
    */
    // Mapping version
    deletion = $$('#pile_right .user').map(function(u) {return u.getText();});
}

// Deselect an user
function userDeselect(user) {
    // Finding the user in the DOM
    if ($type(user) == 'string') {
        var t = $$('.user').filter(function(i) { return (i.getLast().getText() == user); })[0];
    } else if ($type(user) == 'element') {
        var t = user;
        user = t.getLast().getText();
    } else return false;

    t.effect('border-color', {duration: 250}).start('#FFF');
    t.getLast().effects({duration: 250}).start({'background-color':'#FFF','color':'#000'});
    t.addEvent('mouseleave', userHoverdown);
    t.addEvent('mouseenter', userHoverup);
}
